<template>
  <el-dialog
    :model-value="modelValue"
    :title="dialogTitle"
    width="800px"
    @update:model-value="$emit('update:modelValue', $event)"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      label-position="right"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerName">
            <el-input
              v-model="form.customerName"
              placeholder="请输入客户名称"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公司名称" prop="companyName">
            <el-input
              v-model="form.companyName"
              placeholder="请输入公司名称"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户类型" prop="customerType">
            <el-select
              v-model="form.customerType"
              placeholder="请选择客户类型"
              style="width: 100%"
              clearable
            >
              <el-option label="个人" value="Individual" />
              <el-option label="企业" value="Enterprise" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户状态" prop="customerStatus">
            <el-select
              v-model="form.customerStatus"
              placeholder="请选择客户状态"
              style="width: 100%"
              clearable
            >
              <el-option label="活跃" value="Active" />
              <el-option label="非活跃" value="Inactive" />
              <el-option label="黑名单" value="Blacklisted" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户等级" prop="partnerLevelId">
            <el-select
              v-model="form.partnerLevelId"
              placeholder="请选择客户等级"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="level in partnerLevels"
                :key="level.id"
                :label="level.levelName"
                :value="level.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户类别" prop="partnerCategoryId">
            <el-select
              v-model="form.partnerCategoryId"
              placeholder="请选择客户类别"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="category in partnerCategories"
                :key="category.id"
                :label="category.categoryName"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="销售代表" prop="salesRepresentativeId">
            <el-select
              v-model="form.salesRepresentativeId"
              placeholder="请选择销售代表"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="person in salesRepresentatives"
                :key="person.id"
                :label="person.personName || person.name"
                :value="person.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属行业" prop="industryId">
            <el-select
              v-model="form.industryId"
              placeholder="请选择所属行业"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="industry in industries"
                :key="industry.id"
                :label="industry.industryName || industry.name"
                :value="industry.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="业务性质" prop="businessNatureId">
            <el-select
              v-model="form.businessNatureId"
              placeholder="请选择业务性质"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="nature in businessNatures"
                :key="nature.id"
                :label="nature.natureName || nature.name"
                :value="nature.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所在地区" prop="locationId">
            <el-select
              v-model="form.locationId"
              placeholder="请选择所在地区"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="location in locations"
                :key="location.id"
                :label="location.locationName || location.name"
                :value="location.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="信用额度" prop="creditLimit">
            <el-input-number
              v-model="form.creditLimit"
              :min="0"
              :precision="2"
              :step="1000"
              style="width: 100%"
              placeholder="请输入信用额度"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="信用等级" prop="creditRating">
            <el-select
              v-model="form.creditRating"
              placeholder="请选择信用等级"
              style="width: 100%"
              clearable
            >
              <el-option label="A级" value="A" />
              <el-option label="B级" value="B" />
              <el-option label="C级" value="C" />
              <el-option label="D级" value="D" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="付款条件" prop="paymentTerms">
            <el-input
              v-model="form.paymentTerms"
              placeholder="请输入付款条件"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否启用" prop="isEnabled">
            <el-switch
              v-model="form.isEnabled"
              active-text="启用"
              inactive-text="禁用"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注" prop="remarks">
        <el-input
          v-model="form.remarks"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
          clearable
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ mode === 'add' ? '新增' : '更新' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted, computed } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { customerApi } from '@/api/customerApi'
import { getErrorMessage } from '@/utils/error'
import type { Customer, CreateCustomerCommand, UpdateCustomerCommand } from '@/types/customer'
import { fetchAllReferenceLists } from '@/api/referenceApi'

// Props
interface Props {
  modelValue: boolean
  customer: Customer | null
  mode: 'add' | 'edit'
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)

// 下拉选项数据
const partnerLevels = ref([])
const partnerCategories = ref([])
const salesRepresentatives = ref([])
const industries = ref([])
const businessNatures = ref([])
const locations = ref([])
const dropdownLoaded = ref(false)

// 表单数据
const form = reactive<CreateCustomerCommand>({
  customerName: '',
  companyName: '',
  customerType: '' as any,
  customerStatus: '' as any,
  partnerLevelId: undefined,
  partnerCategoryId: undefined,
  salesRepresentativeId: undefined,
  industryId: undefined,
  businessNatureId: undefined,
  locationId: undefined,
  creditLimit: 0,
  creditRating: '' as any,
  paymentTerms: '',
  remarks: '',
  isEnabled: true
})

// 表单验证规则
const rules: FormRules = {
  customerName: [
    { required: true, message: '请输入客户名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  companyName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ],
  customerType: [
    { required: true, message: '请选择客户类型', trigger: 'change' }
  ],
  customerStatus: [
    { required: true, message: '请选择客户状态', trigger: 'change' }
  ],
  creditRating: [
    { required: true, message: '请选择信用等级', trigger: 'change' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return props.mode === 'add' ? '新增客户' : '编辑客户'
})

// 方法
const loadDropdownData = async () => {
  try {
    dropdownLoaded.value = false
    const lists = await fetchAllReferenceLists()
    partnerLevels.value = lists.levels
    partnerCategories.value = lists.categories
    salesRepresentatives.value = lists.persons
    industries.value = lists.industries
    businessNatures.value = lists.natures
    locations.value = lists.locations
  } catch (error: unknown) {
    const msg = getErrorMessage(error)
    ElMessage.error(`加载下拉选项失败: ${msg}`)
  } finally {
    dropdownLoaded.value = true
  }
}

const resetForm = () => {
  Object.assign(form, {
    customerName: '',
    companyName: '',
    customerType: '' as any,
    customerStatus: '' as any,
    partnerLevelId: undefined,
    partnerCategoryId: undefined,
    salesRepresentativeId: undefined,
    industryId: undefined,
    businessNatureId: undefined,
    locationId: undefined,
    creditLimit: 0,
    creditRating: '' as any,
    paymentTerms: '',
    remarks: '',
    isEnabled: true
  })
}

const fillForm = (customer: Customer) => {
  const toNum = (v: any) => (v === null || v === undefined || v === '' ? undefined : Number(v))
  Object.assign(form, {
    customerName: (customer as any).customerName || '',
    companyName: (customer as any).companyName || '',
    customerType: (customer as any).customerType === 1 ? 'Individual' : ((customer as any).customerType === 2 ? 'Enterprise' : ((customer as any).customerType || '' as any)),
    customerStatus: (customer as any).customerStatus === 1 ? 'Active' : ((customer as any).customerStatus === 2 ? 'Inactive' : ((customer as any).customerStatus === 3 ? 'Blacklisted' : ((customer as any).customerStatus || '' as any))),
    partnerLevelId: toNum((customer as any).partnerLevelId ?? (customer as any).customerLevelId),
    partnerCategoryId: toNum((customer as any).partnerCategoryId ?? (customer as any).customerCategoryId),
    salesRepresentativeId: toNum((customer as any).salesRepresentativeId),
    industryId: toNum((customer as any).industryId),
    businessNatureId: toNum((customer as any).businessNatureId),
    locationId: toNum((customer as any).locationId),
    creditLimit: Number((customer as any).creditLimit ?? 0),
    creditRating: (customer as any).creditRating || '' as any,
    paymentTerms: (customer as any).paymentTerms ?? '',
    remarks: (customer as any).remarks || '',
    isEnabled: (customer as any).isEnabled ?? true
  })
}

const ensureDropdownsThenFill = async (customer: Customer) => {
  if (!dropdownLoaded.value) {
    await loadDropdownData()
  }
  fillForm(customer)
}

const loadDetailAndFill = async () => {
  try {
    if (props.mode !== 'edit') return
    const rawId = (props.customer as any)?.id ?? (props.customer as any)?.Id
    if (!rawId) return
    if (!dropdownLoaded.value) await loadDropdownData()
    const id = Number(rawId)
    const res = await customerApi.getCustomerById(id)
    if (res.code === 200 && res.data) {
      const d: any = res.data
      const normalized: any = {
        id: d.id ?? d.Id,
        customerName: d.customerName ?? d.CustomerName,
        companyName: d.companyName ?? d.CompanyName,
        customerType: d.customerType ?? d.CustomerType,
        customerStatus: d.customerStatus ?? d.CustomerStatus,
        partnerLevelId: d.partnerLevelId ?? d.customerLevelId ?? d.CustomerLevelId,
        partnerCategoryId: d.partnerCategoryId ?? d.customerCategoryId ?? d.CustomerCategoryId,
        salesRepresentativeId: d.salesRepresentativeId ?? d.SalesRepresentativeId,
        industryId: d.industryId ?? d.IndustryId,
        businessNatureId: d.businessNatureId ?? d.BusinessNatureId,
        locationId: d.locationId ?? d.LocationId,
        creditLimit: d.creditLimit ?? d.CreditLimit,
        creditRating: d.creditRating ?? d.CreditRating,
        paymentTerms: d.paymentTerms ?? d.PaymentTerms ?? d.paymentCondition ?? d.PaymentCondition ?? d.paymentTerms ?? d.PaymentTerms ?? '',
        remarks: d.remarks ?? d.Remarks,
        isEnabled: d.isEnabled ?? d.IsEnabled
      }
      fillForm(normalized)
    }
  } catch (e: unknown) {
    const msg = getErrorMessage(e)
    ElMessage.error(`加载客户详情失败: ${msg}`)
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    let response
    if (props.mode === 'add') {
      response = await customerApi.createCustomer({
        ...form,
        isEnabled: form.isEnabled ?? true, // 确保isEnabled字段存在
        paymentTerms: typeof form.paymentTerms === 'string' ? (parseInt(form.paymentTerms as any, 10) || null) : (form.paymentTerms as any)
      })
    } else {
      if (!props.customer?.id) {
        throw new Error('客户ID不能为空')
      }
      const updateData: UpdateCustomerCommand = {
        id: props.customer.id,
        ...form,
        isEnabled: form.isEnabled ?? true, // 确保isEnabled字段存在
        paymentTerms: typeof form.paymentTerms === 'string' ? (parseInt(form.paymentTerms as any, 10) || null) : (form.paymentTerms as any)
      }
      response = await customerApi.updateCustomer(updateData)
    }
    
    if (response.code === 200) {
      ElMessage.success(props.mode === 'add' ? '新增成功' : '更新成功')
      emit('success')
    } else {
      throw new Error(response.message || '操作失败')
    }
  } catch (error: unknown) {
    if (error !== 'cancel') {
      const msg = getErrorMessage(error)
      ElMessage.error(`操作失败: ${msg}`)
    }
  } finally {
    submitting.value = false
  }
}

const handleClose = () => {
  resetForm()
  emit('update:modelValue', false)
}

// 监听器
watch(
  () => props.customer,
  (newCustomer) => {
    if (newCustomer && props.mode === 'edit') {
      // 如果父级只传了部分字段，进入弹窗时再拉取详情补齐
      loadDetailAndFill()
    } else {
      resetForm()
    }
  },
  { immediate: true }
)

watch(
  () => props.modelValue,
  (open) => {
    if (open && props.mode === 'edit') {
      loadDetailAndFill()
    }
  }
)

watch(dropdownLoaded, (ready) => {
  if (ready && props.customer && props.mode === 'edit') {
    // 再次确保填充（防止选项未加载导致显示为空）
    loadDetailAndFill()
  }
})

// 生命周期
onMounted(() => {
  loadDropdownData()
})
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number) {
  width: 100%;
}
</style> 